import axios from "axios";
//加密token
import { Base64 } from "js-base64";
//消息弹出框
import { ElMessageBox } from "element-plus";

//创建axios 通用配置
let instance = axios.create({
    responseType: "json",
    headers: { "Content-Type": "application/json" }, // 这里是拼写已更正的地方
});

//对token加密
function baseFun() {
    const token = localStorage.getItem("token");
    const base64 = Base64.encode(token + ":");
    return "Basic " + base64;
}
//http拦截器：请求发出之前给每个接口携带token去后端校验身份
// instance.interceptors.request.use(
//     (config) => {
//         let token = localStorage.getItem("token");
//         if (token) {
//             config.headers.Authorization = baseFun();
//         }

//         return config;
//     },
//     (err) => {
//         return Promise.reject(err);
//     }
// );

//http拦截器：请求发出之前给每个接口携带token去后端校验身份
instance.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem("token");
        if (token) {
            // 检查token是否过期
            const expirationTime = localStorage.getItem("expirationTime")+(30 * 60 * 1000); ;
            const currentTime = new Date().getTime();
            if (expirationTime && parseInt(expirationTime) < currentTime) {
                // token过期，执行登出操作或者其他相关操作
                // 这里假设执行了登出操作，并清除了token和过期时间
                localStorage.removeItem("token");
                localStorage.removeItem("expirationTime");
               
                
            } else {
                // token未过期，将token携带到请求头中
                config.headers.Authorization = baseFun();
            }
        }

        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

//http拦截器：请求发出之后

instance.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        if (error.response) {
            let ERRS = error.response.status;
            //console.log(error.response.data.msg);
            //let MSG = error.response.data.msg.msg;
            //console.log(error.response.data.error);
            let MSG = error.response.data.error;
            let errData = ERRS == 401 ? MSG : "服务器发生错误";
            //console.log(errData);
            switch (ERRS) {
                case 401:
                    ElMessageBox.alert(errData, "提示", {
                            confirmButtonText: "好的",
                            type: "error",
                        })
                        .then((res) => {
                            //跳转到登录界面
                            window.location.href = "/";
                        })
                        .catch((err) => {
                            //console.log(err);
                            window.location.href = "/";
                        });
                    break;
            }
        }
        //返回接口的错误信息
        //console.log(error);
        return Promise.resolve(error.response.data);
    }
);
export default instance;